package cn.edu.sbs.talent.shiro.filter;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * TalentRolesAuthorizationFilter
 *
 * @author ctidy
 * @since 2021/1/7
 */
public class AnyRolesAuthorizationFilter extends AuthorizationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;

        // 没有角色要求, 不做限制
        if (ObjectUtils.isEmpty(rolesArray)) {
            return true;
        }

        for (String s : rolesArray) {
            // 属于任何一个角色, 直接放行
            if (subject.hasRole(s)) {
                return true;
            }
        }
        return false;
    }
}
